package com.crr;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Productor {
    public static void main(String[] args) {
        //1创建连接工厂 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("/");
        factory.setPort(5672);
        factory.setUsername("user");
        factory.setPassword("chen1116.");
        // factory.setHost("127.0.0.1");

        //2创建连接
        try (Connection conn = factory.newConnection();
             //3创建信道
             Channel channel = conn.createChannel()) {
            //4 启用发布确认
            channel.confirmSelect();
            //接收服务器确认的消息
            channel.addConfirmListener((deliveryTag, multiple) -> {
                System.out.println("服务器确认消息：" + deliveryTag);
            }, (deliveryTag, multiple) -> {
                System.out.println("服务器没有收到消息：" + deliveryTag);
            });
            //声明队列
            String queueName = "confirm_single";

            channel.queueDeclare(queueName, false, false, false, null);
            long begin = System.currentTimeMillis();

            AMQP.BasicProperties.Builder properties = MessageProperties.PERSISTENT_TEXT_PLAIN.builder()
                    .deliveryMode(2);
            //发送消息
            for (int i = 1; i <= 1000; i++) {
                channel.basicPublish("", queueName, null, ("发布确认" + i).getBytes());
                channel.waitForConfirmsOrDie(5000);
            }
            long end = System.currentTimeMillis();
            System.out.println("耗费时间："+(end - begin));
            System.out.println("消息已发送,信息已收到");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

}
